<template>
  <div class="container">
    <button @click="openConnect" v-if="!isConnected">打开连接</button>
    <button @click="closeConnect" v-if="isConnected">关闭连接</button>
    <label for="input" v-if="isConnected">
      <input id="input" v-model="message" />
      <button @click="sendMessage">发送信息</button>
    </label>
    <ul>
      <li v-for="(item, index) in messageList" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>
 
 <script>
export default {
  data() {
    return {
      message: null, //当前输入消息
      messageList: [], //消息列表
      // messageList: [{ id: 111, type: 0 },{ id: 2222, type: 1 },{ id: 333, type: 2 }],
      ws: null, //ws实例
      isConnected: false, //是否处于连接
      // isConnected: true, //是否处于连接
    }
  },
  methods: {
    /**
     *@dec 打开连接
     */
    openConnect() {
      if ('WebSocket' in window) {
        //判定ws兼容
        const ws = new WebSocket('ws://localhost:8080') //地址为服务器接口地址

        ws.onopen = () => {
          // 连接成功时
          this.isConnected = true
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          ws.send('{"sceneid":2000}')
        }

        ws.onmessage = evt => {
          // 发送信息时
          this.messageList.push(JSON.parse(evt.data))
        }

        ws.onclose = () => {
          // 关闭连接时
          this.isConnected = false
        }

        ws.onerror = err => {
          // 连接错误时
          console.log('err', err)
          this.isConnected = false
        }

        this.ws = ws
      } else {
        alert('您的浏览器不支持 WebSocket!')
      }
    },

    /**
     *@dec 发送信息
     */
    sendMessage() {
      if (this.ws && this.message) {
        this.ws.send(this.message)
        this.message = ''
      }
    },

    /**
     *@dec 关闭连接
     */
    closeConnect() {
      if (this.ws) this.ws.close()
    },
  },
}
</script>
 
 <style scoped lang="less">
.container {
  button {
    color: #000;
  }
}
</style>